<?php
class UrlCommon {
	
	// 将用户ID转换为三级路径
	function convertUidToPath($uid) {
		return '/' . $uid;
	}
	function getContentUrl($url) {
		return common ( 'Url' )->getShortUrl ( $url [1] ) . ' ';
	}
	function getShortUrl($url) {
		return common ( 'Url' )->getShort ( htmlspecialchars_decode ( $url ) );
	}
	
	/**
	 * 获取用户头像
	 * M2
	 * 
	 * @param int $uid
	 *        	用户ID
	 * @param string $size
	 *        	头像大小 m:中图 | s:小图 | 其它:大图
	 * @return string 头像的URL地址
	 */
	function getUserFace($uid, $size, $width = 66, $height = 66) {
		$size = ($size) ? $size : 'm';
		if ($size == 'm') {
			$type = 'middle';
		} elseif ($size == 's') {
			$type = 'small';
			$width = 42;
			$height = 42;
		} else {
			$type = 'big';
		}
		$uid_to_path = common ( 'Url' )->convertUidToPath ( $uid );
		$userface = './data/uploads/avatar' . $uid_to_path . '/' . $type . '.jpg';
		
		if (is_file ( $userface )) {
			$face = __ROOT__.'/data/uploads/avatar' . $uid_to_path . '/' . $type . '.jpg';
		} else {
			$userface = './data/uploads/avatar/0/' . $type . '.jpg';
			$face = __ROOT__.'/data/uploads/avatar/0/' . $type . '.jpg';
		}
		return "<img src=" . $face .'?'.filemtime($userface). " width='" . $width . "' height='" . $height . "'><i class='avatar-bg'></i>";
	}
	function getShort($str, $length = 40, $ext = '') {
		$str = htmlspecialchars ( $str );
		$str = strip_tags ( $str );
		$str = htmlspecialchars_decode ( $str );
		$strlenth = 0;
		$out = '';
		preg_match_all ( "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/", $str, $match );
		foreach ( $match [0] as $v ) {
			preg_match ( "/[\xe0-\xef][\x80-\xbf]{2}/", $v, $matchs );
			if (! empty ( $matchs [0] )) {
				$strlenth += 1;
			} elseif (is_numeric ( $v )) {
				$strlenth += 0.5; // 字符字节长度比例 汉字为1
			} else {
				$strlenth += 0.5; // 字符字节长度比例 汉字为1
			}
			
			if ($strlenth > $length) {
				$output .= $ext;
				break;
			}
			
			$output .= $v;
		}
		return $output;
	}
	
	function hasUserFace($uid) {
		$type="big";
		$uid_to_path = common ( 'Url' )->convertUidToPath ( $uid );
		$userface = './data/uploads/avatar' . $uid_to_path . '/' . $type . '.jpg';		
		if (is_file ( $userface )) {
			$face = SITE_URL.'/data/uploads/avatar' . $uid_to_path . '/' . $type . '.jpg';
		} else {
			$face = SITE_URL.'/data/uploads/avatar/0/' . $type . '.jpg';
		}
		return $face;
	}
	
	/**
	 * 返回解析的空间地址
	 * M2
	 * 
	 * @param int $uid
	 *        	用户ID
	 * @param string $class
	 *        	class样式
	 * @param string $target
	 *        	跳转方式
	 * @param string $text
	 *        	用户头像
	 * @param boolean $icon        	
	 * @return string 返回解析的空间地址
	 */
	function getUserSpace($uid, $class, $target, $text, $icon = true, $user_name, $showcard) {
		static $_userinfo = array ();
		if (! isset ( $_userinfo [$uid] )) {
			$_userinfo [$uid] = model ( 'User' )->getUserByIdentifier ( $uid, 'uid' );
		}
		$target = ($target) ? $target : '_self';
		$text = ($text) ? $text : $_userinfo [$uid] ['uname'];
		
		preg_match ( '|{(.*?)}|isU', $text, $t );
		
		if ($t) {
			if ($t ['1'] == 'uname') {
				$text = str_replace ( "{uname}", $_userinfo [$uid] ['uname'], $text );
				$class = ($class) ? $class : 'username';
			} else {
				$face = preg_replace ( "/{uavatar}|{uavatar\\=(.*?)}/e", "getUserFace(\$uid, '\\1')", $text );
				$text = $face;
				$class = ($class) ? $class : 'userface';
				$icon = false;
			}
		}
		
		if ($icon) {
			$user_name_end = null;
		}
		
		if ($user_name) {
			$user_name = "<span class='name'>" . common ( 'String' )->getShort ( common ( 'String' )->getUserName ( $uid ), 3, '...' ) . "</span>";
		}
		if (session ( '?mid' )) {
			if (session ( 'mid' ) != $uid) {
				if ($showcard) {
					$showcard = "onmouseover='card.showCard(this," . $uid . ")'";
				}
			}
		} else {
			if ($showcard) {
				$showcard = "onmouseover='card.showCard(this," . $uid . ")'";
			}
		}
		
		if ($_userinfo [$uid] ['domain'])
			$url = URL ( 'home/Space/index', array (
					'uid' => $_userinfo [$uid] ['domain'] 
			) );
		else
			$url = URL ( 'home/Space/index', array (
					'uid' => $uid 
			) );
		
		$user_space_info = "<a href='{$url}' class='{$class}' target='{$target}' {$showcard}>$text" . $user_name_end . $user_name . "</a>";
		return $user_space_info;
	}
	
	/**
	 * 获取用户头像路径
	 * @param int    $uid  用户ID
	 * @param string $size 头像大小 m:中图 | s:小图 | 其它:大图
	 * @return string 头像的URL地址
	 */
	function getUserFaceUrl($uid, $size) {
		$size = ($size) ? $size : 'm';
		if ($size == 'm') {
			$type = 'middle';
		}elseif ($size == 's') {
			$type = 'small';
		}elseif ($size == 'o') {
			$type = 'original';
		}elseif ($size == 'b') {
			$type = 'big';
		}elseif ($size == 'bg') {
			$type = 'background';
		}elseif ($size == 'a') {
			$type = 'api';
		} else {
			$type = 'big';
		}
		$uid_to_path = common('Url')->convertUidToPath($uid);
		$userface = './data/uploads/avatar' . $uid_to_path . '/' . $type . '.jpg';
		if (is_file($userface)) {
			$face = __ROOT__.'/data/uploads/avatar' . $uid_to_path . '/' . $type . '.jpg';
		} else {
			if ($size == 'a'){
				$userface = './data/uploads/avatar' . $uid_to_path . '/big.jpg';
				if (is_file($userface)) {
					$face = __ROOT__.'/data/uploads/avatar' . $uid_to_path . '/big.jpg';
				} else {
					$userface='./data/uploads/avatar/0/' . $type . '.jpg';
					$face = __ROOT__.'/data/uploads/avatar/0/'.$type.'.jpg';
				}
			}else{
				$userface='./data/uploads/avatar/0/' . $type . '.jpg';
				$face = __ROOT__.'/data/uploads/avatar/0/'.$type.'.jpg';
			}
		}
		return $face.'?'.filemtime($userface);
	}
	
	/**
	 * 返回请求地址的通信状态
	 * M2
	 * 
	 * @param string $url
	 *        	请求地址
	 * @param string $ip
	 *        	请求IP
	 */
	function test_api($url, $ip = '') {
		if (! $ip) {
			$ip = common ( 'Url' )->get_host_by_url ( $url );
		}
		
		if ($ip < 0) {
			return FALSE;
		}
		return common ( 'Url' )->dfopen ( $url, 0, '', '', 1, $ip );
	}
	
	/**
	 * 返回请求地址的IP
	 * M2
	 * 
	 * @param $url string
	 *        	请求地址
	 */
	function get_host_by_url($url) {
		$m = parse_url ( $url );
		if (! $m ['host']) {
			return - 1;
		}
		if (! preg_match ( "/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $m ['host'] )) {
			$ip = @gethostbyname ( $m ['host'] );
			if (! $ip || $ip == $m ['host']) {
				return - 2;
			}
			return $ip;
		} else {
			return $m ['host'];
		}
	}
	
	/**
	 * 打开Internet的socket连接
	 * M2
	 * 
	 * @param        	
	 *
	 */
	function dfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE') {
		$return = '';
		$matches = parse_url ( $url );
		$host = $matches ['host'];
		$path = $matches ['path'] ? $matches ['path'] . ($matches ['query'] ? '?' . $matches ['query'] : '') : '/';
		$port = ! empty ( $matches ['port'] ) ? $matches ['port'] : 80;
		$out = "GET $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host:$port\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
		if (function_exists ( 'fsockopen' )) {
			$fp = @fsockopen ( ($ip ? $ip : $host), $port, $errno, $errstr, $timeout );
		} elseif (function_exists ( 'pfsockopen' )) {
			$fp = @pfsockopen ( ($ip ? $ip : $host), $port, $errno, $errstr, $timeout );
		} else {
			$fp = false;
		}
		if (! $fp) {
			return '';
		} else {
			stream_set_blocking ( $fp, $block );
			stream_set_timeout ( $fp, $timeout );
			@fwrite ( $fp, $out );
			$status = stream_get_meta_data ( $fp ); // 获取请求地址的头部信息
			if (! $status ['timed_out']) {
				while ( ! feof ( $fp ) ) {
					if (($header = @fgets ( $fp )) && ($header == "\r\n" || $header == "\n")) {
						break;
					}
				}
				$stop = false;
				while ( ! feof ( $fp ) && ! $stop ) {
					$data = fread ( $fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit) );
					$return .= $data;
					if ($limit) {
						$limit -= strlen ( $data );
						$stop = $limit <= 0;
					}
				}
			}
			@fclose ( $fp );
			return $return;
		}
	}
	function get_url_code($action, $getdata, $appid) {
		$data ['appid'] = $appid;
		$apps = model ( 'Applications' )->get_apps ( $data );
		$authkey = $apps [0] ['authkey'];
		$url = $apps [0] ['url'];
		$apifilename = 'uc.php';
		$action = 'action=' . $action;
		$code = urlencode ( common ( 'String' )->authcode ( "$action&" . ($getdata ? "$getdata&" : '') . "time=" . time (), 'ENCODE', $authkey ) );
		return $url . "/api/$apifilename?code=$code";
	}
	
	/**
	 * 检查URL输入是否合法
	 * 
	 * @param string $url
	 *        	url地址
	 */
	function check_url($url) {
		return preg_match ( "/(https?){1}:\/\/|www\.([^\[\"']+?)?/i", $url );
	}
	
	/**
	 * 检查IP地址输入是否合法
	 * 
	 * @param string $url
	 *        	ip地址
	 */
	function check_ip($url) {
		return preg_match ( "/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $url );
	}
	
	/**
	 * 获取同步操作的URL
	 * M2
	 * 
	 * @param        	
	 *
	 */
	function getSysOperUrl($fun, $data = array()) {
		if (empty ( $data )) {
			$body = '';
		} else {
			foreach ( $data as $k => $v ) {
				$a [] = urlencode ( $k ) . "=" . urlencode ( $v );
			}
			$body = implode ( "&", $a );
		}
		$statusList = common ( 'Url' )->onping ();
		foreach ( $statusList as $k => $v ) {
			$strUrl = common ( 'Url' )->get_url_code ( $fun, $body, $v ['appid'] );
			echo '<script type="text/javascript" src="' . $strUrl . '"></script>';
		}
	}
	
	/**
	 * 获取通信正常的数据
	 * M2
	 * 
	 * @param        	
	 *
	 */
	function onping() {
		// 获取所有应用
		$list = model ( 'Applications' )->get_apps ();
		$statusList = array ();
		foreach ( $list as $k => $v ) {
			$url = common ( 'Url' )->get_url_code ( 'test', '', $v ['appid'] );
			$status = common ( 'Url' )->test_api ( $url, $v ['ip'] );
			// 获取通信成功的数据
			if ($status == '1') {
				// 如果是初始化数据的话则跳出，返回和本应用通信正常的数据
				if ($v ['appid'] == 1) {
					continue;
				}
				$statusList [] = $v;
			}
		}
		return $statusList;
	}
	
	/**
	 * 获取用户头像
	 * M2
	 *
	 * @param int $uid
	 *        	用户ID
	 * @param string $size
	 *        	头像大小 m:中图 | s:小图 | 其它:大图
	 * @return string 头像的URL地址
	 */
	function getMUserFace($uid, $size) {
		$sizeurl = 'http://avatar.i8i8i8.com';
		$size = ($size) ? $size : 'a';
		if ($size == 'm') {
			$type = 'middle';
		} elseif ($size == 's') {
			$type = 'small';
		} elseif ($size == 'bg') {
			$type = 'background';
		} elseif ($size == 'a') {
			$type = 'api';
		}else {
			$type = 'api';
		}
		$uid_to_path = common('Url')->convertUidToPath($uid);
		$userface = '/avatar' . $uid_to_path . '/' . $type . '.jpg';
	
		if (@fopen( $sizeurl.$userface, 'r' )) {
			$fileheaders = get_headers($sizeurl.$userface,1);
			$face = $sizeurl.'/avatar' . $uid_to_path . '/' . $type . '.jpg'."?".strtotime($fileheaders['Last-Modified']);
		} else {
			$face = $sizeurl.'/avatar/0/' . $type . '.jpg';
		}
		return $face ;
	}
}
?>